/**
 * 测试服务配置
 * @author Wanghui <wangh@ciqtek.com>
 * @company ubiot.cn
 * @date 2019-06-20
 */

let WebSocketServer = require('websocket').server
let http = require("http")
let fs = require("fs")
let path = require("path")
const _ = require("lodash")

let server = http.createServer(function(request, response) {
  console.log((new Date()) + ' Received request for ' + request.url)
  response.writeHead(404)
  response.end()
})
let port = 9988

server.listen(port, function() {
  console.log(`${new Date()} Server is listening on port ${port}`)
})

wsServer = new WebSocketServer({
  httpServer: server,
  autoAcceptConnections: false
})

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true
}

/**
 * 载入指令处理函数
 * @type {{}}
 */
let directiveControllerMap = {
  // 指令: handler
}
for ( let filePath of fs.readdirSync(__dirname) ) {
  if (/index.js/gi.test(filePath)) continue;
  console.log('load directive controller : ' + filePath)
  directiveControllerMap[filePath.replace('.js', '')] = require(path.resolve(__dirname, filePath))
}

function _onMessage(ws, event) {
  console.log('receive: ' + event.utf8Data);
  let msg = JSON.parse(event.utf8Data);

  // 交给定义好的处理方法处理
  try {
    _.get(directiveControllerMap, msg.type)(ws, msg)
  } catch (ignore) {}
}


wsServer.on('request', function(request) {
  if (!originIsAllowed(request.origin)) {
    // Make sure we only accept requests from an allowed origin
    request.reject();
    console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
    return;
  }

  let connection = request.accept('echo-protocol', request.origin);
  console.log((new Date()) + ' Connection accepted.');

  connection.on('message', function(message) {
    if (message.type === 'utf8') {
      try {
        _onMessage(connection, message)
      } catch (err) {
        console.error(err)
      }
    }
    else if (message.type === 'binary') {
      console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
      connection.sendBytes(message.binaryData);
    }
  });

  connection.on('close', function(reasonCode, description) {
    console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
  });
})
